package com.frank.code_notes.C02_LinkedList;


import cn.hutool.core.lang.Console;
import com.frank.utils.ListNode;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @Description 19.删除链表的倒数第N个节点
 * @Author zhoujr
 * @Data 2024/12/5 21:30
 */
public class L019RemoveLinkedNode {

    public  static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(-1, head);
        ListNode fast = head, slow = dummyHead;

        while (fast.next != null) {
            if (--n < 1)  {
                slow = slow.next;
            };
            fast = fast.next;
        }
        if (slow != null && slow.next != null) {
            slow.next = slow.next.next;
        };
        return dummyHead.next;
    }

    public static void nodePrint(ListNode cur) {
        if (cur == null) return;
        Console.log(cur.val);
        nodePrint(cur.next);

    }

    public static void main(String[] args) {
        ListNode listNode = removeNthFromEnd(ListNode.toListNode(new ArrayList<>(Arrays.asList(1, 2, 3, 4))), 1);
        nodePrint(listNode);
    }

}
